package com.diaohw.module.system.service.impl;

import com.diaohw.module.system.mapper.SysMenuMapper;
import com.diaohw.module.system.obj.dto.SysMenuDTO;
import com.diaohw.module.system.obj.entity.SysMenuDO;
import com.diaohw.module.system.obj.mapstruct.SysMenuMapstruct;
import com.diaohw.module.system.obj.query.SysMenuQuery;
import com.diaohw.module.system.obj.vo.RouteVO;
import com.diaohw.module.system.obj.vo.SysMenuVO;
import com.diaohw.module.system.service.SysMenuService;
import com.diaohw.platform.common.obj.page.PageResultVo;
import com.diaohw.platform.common.util.TreeUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 部门 服务实现类
 * </p>
 *
 * @author D-Hw
 * @since 2024-07-05
 */
@Service
public class SysMenuImpl implements SysMenuService {

    @Resource
    private SysMenuMapper sysMenuMapper;

    @Override
    public SysMenuVO create(SysMenuDTO data) {
        SysMenuDO model = SysMenuMapstruct.INSTANCE.toEntity(data);
        sysMenuMapper.insert(model);
        return SysMenuMapstruct.INSTANCE.toVO(model);
    }

    @Override
    public SysMenuVO update(String id, SysMenuDTO data) {
        SysMenuDO model = SysMenuMapstruct.INSTANCE.toEntity(data);
        model.setId(id);
        sysMenuMapper.update(model);
        return SysMenuMapstruct.INSTANCE.toVO(model);

    }

    @Override
    public Boolean delete(String id) {
        return sysMenuMapper.deleteById(id) > 0;
    }

    @Override
    public SysMenuVO detail(String id) {
        SysMenuDO model = sysMenuMapper.selectOneById(id);
        return SysMenuMapstruct.INSTANCE.toVO(model);

    }

    @Override
    public List<SysMenuVO> findByList(SysMenuQuery query) {
        QueryWrapper wrapper = SysMenuMapper.createWrapper(query);
        List<SysMenuDO> list = sysMenuMapper.selectListByQuery(wrapper);
        return SysMenuMapstruct.INSTANCE.toVOList(list);

    }

    @Override
    public PageResultVo<SysMenuVO> findByPage(SysMenuQuery query) {
        QueryWrapper wrapper = SysMenuMapper.createWrapper(query);
        Page<SysMenuDO> page = sysMenuMapper.paginate(query.getPageIndex(), query.getPageSize(), wrapper);
        List<SysMenuDO> records = page.getRecords();
        return PageResultVo.create(page.getTotalRow(), SysMenuMapstruct.INSTANCE.toVOList(records));
    }


    @Override
    public List<RouteVO> routes() {
        SysMenuQuery query = new SysMenuQuery();
        query.setType(List.of(SysMenuDO.TYPE_MENU, SysMenuDO.TYPE_CATALOG, SysMenuDO.TYPE_LINK));
        QueryWrapper wrapper = SysMenuMapper.createWrapper(query);
        List<SysMenuDO> menuList = sysMenuMapper.selectListByQuery(wrapper);

        List<RouteVO> list = SysMenuMapstruct.INSTANCE.toRouteList(menuList);

        return TreeUtil.listToTree(list, RouteVO::getId, RouteVO::getParentId, RouteVO::getChildren);
    }
}
